//
//  ViewController.swift
//  Checked
//
//  Created by admin on 01/03/2017.
//  Copyright © 2017 shinolr_go. All rights reserved.
//

import UIKit
import Moya
import SwiftyJSON

class ViewController: UIViewController, UIWebViewDelegate {

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view, typically from a nib.

		view.backgroundColor = UIColor.lightGray
		setupLoginPage()

		let dateFormatter = DateFormatter()
		dateFormatter.dateFormat = "yy-MM-dd"
		print(dateFormatter.string(from: Date()))
	}

	private lazy var webView: UIWebView = {
		let webView = UIWebView.init(frame: self.view.bounds)
		webView.delegate = self
		return webView
	}()

	var code: String?

	private func setupLoginPage() {
		let urlStr = "https://trakt.tv/oauth/authorize?response_type=code&client_id=\(clientID)&redirect_uri=\(redirect_uri)"

		view.addSubview(webView)
		webView.loadRequest(URLRequest(url: URL(string: urlStr)!))
	}

	// MARK: - webView delegate
	func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

		guard let url = request.url else {
			return false
		}

		if !url.absoluteString.hasPrefix(redirect_uri) {
			print(url)
			return true
		}

		if let query = url.query, query.hasPrefix("code=") {
			let startIndex = "code=".endIndex
			code = query.substring(from: startIndex)

			print("code: \(code)")

			// MARK: - 请求授权
//			provider.request(.authorize, completion: { (result) in
//				switch result {
//				case let .success(moyaResponse):
//					let data = moyaResponse.data
//					let json = JSON(data: data)
//					let response = moyaResponse.response
//					let request = moyaResponse.request
//					print("request:\(request)")
//					print("response:\(response)")
//					print("moyaResponse:\(moyaResponse)")
//					print("data:\(data)")
//					print("json:\(json)")
//				case let .failure(error):
//					print("error: \(error)")
//				}
//			})

			// MARK: - 请求 accessToken
//			provider.request(.accessToken(code: code!), completion: { (result) in
//				switch result {
//				case let .success(moyaResponse):
//					let data = moyaResponse.data
//					let json = JSON(data: data)
//					print("json: \(json)")
//
//				case let .failure(error):
//					print ("error: \(error)")
//				}
//			})

		}
		return false
	}

	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}
}
